"use strict";

var C = require('../common');

module.exports = {

    type: 'module',

    load: function (owner, routes, cb) {

        var baseRoute = C.trimRightSlash(owner.route);
        var routers = [];

        C._.each(routes, function (routersConfig, route) {
            var mount = baseRoute + C.trimRightSlash(C.ensureLeftSlash(route));

            C._.each(routersConfig, function (options, type) {
                routers.push({
                    type: type,
                    router: owner.loadExtension('router_modules', type),
                    mount: mount,
                    options: routersConfig[type] });
            });
        });

        C.async.eachSeries(routers, function (item, cb2) {
            owner.console('Mounting a "' + item.type + '" router at "' + item.mount + '" ...');
            item.router.mount(owner, item.mount, item.options, function (err) {
                if (err) return cb2(err);

                owner.console('A "' + item.type + '" router is successfully mounted at "' + item.mount + '".');
                cb2();
            });
        }, cb);
    }
};